<template>
  <div class="app-container">
    <!-- <t-Search /> -->
    <el-form :model="param" ref="publishRef" :rules="publishRules" label-width="0">
      <el-card class="form_card">
        <span class="_before">基本信息</span>
        <div style="margin:40px 40px 0 40px">
          <el-row style="width:600px;min-width: 400px;">
            <el-col :span="11">
              <el-form-item prop="boxStartCity">
                <div>
                  <redStar />提箱城市
                </div>
                <city-select ref="startCityRef" v-model="param.boxStartCity" :needInfo="true" :cityList="startCityList"
                  @cityId="startCityInfo" @clear="cityClear('start')" :disabled="param.status || isInfo" style="width: 100%;"></city-select>
              </el-form-item>
            </el-col>
            <el-col :span="2" style="text-align: center;margin-top: 40px; ">
              <svg-icon icon-class="toRight" />
            </el-col>
            <el-col :span="11">
              <el-form-item prop="boxBackCity" >
                <div>
                  <redStar />还箱城市
                </div>
                <city-select ref="backCityRef" v-model="param.boxBackCity" :needInfo="true" :cityList="backCityList"
                  @cityId="backCityInfo" @clear="cityClear('end')" :disabled="param.status || isInfo" style="width: 100%;"></city-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <el-card class="form_card" style="margin-top: 15px;">
        <span class="_before">出租信息</span>
        <div style="margin:40px 40px 0 40px">
          <el-form-item>
            <div style="width:100%">
              <redStar />出租箱规格
            </div>
            <boxPriceList ref="boxPriceListRef" :priceList="param.dynamicTags" :disabled="!param.boxStartCity || isInfo"
              :isRent="true" :numArry="param.numArry" :isOutBox="param.isOutBox" @currency="publishCurrency">
            </boxPriceList>
          </el-form-item>
          <el-form-item prop="payCurrency">
            <div style="width:100%">
              <redStar />可结算币种
            </div>
            <el-checkbox-group v-model="param.payCurrency" :disabled="isInfo"> 
              <el-checkbox label="人民币（CNY）" value="CNY" :disabled="param.isCheckCNY"/>
              <el-checkbox label="美元（USD）" value="USD" :disabled="param.isCheckUSD"/>
            </el-checkbox-group>
          </el-form-item>
    
          <el-form-item prop="overdueFeeDay">
            <div style="width: 100%;">
              <redStar />超期费
            </div>
            <span>超期1天后 $
              <el-input-number v-model.trim="param.overdueFeeDay" :disabled="isInfo" :controls="false" :min="0" :max="999" :precision="0"
                placeholder="< 1000" style="width: 80px" />
            </span>&nbsp; 箱/天
          </el-form-item>
          <el-row>
            <el-form-item prop="lossDay" style="float: left;">
              超期 &nbsp;
              <el-input-number v-model.trim="param.lossDay" :disabled="isInfo" :controls="false" :min="0" :max="999" :precision="0"
                placeholder="< 1000" style="width: 80px" />
              &nbsp;天后，仍未还箱，视为灭失，灭失费为
            </el-form-item>
            <el-form-item prop="lossFee">
              &nbsp;$&nbsp;
              <el-input-number v-model.trim="param.lossFee" :disabled="isInfo" :controls="false" :min="0" :max="9999" :precision="0"
                placeholder="< 10000" style="width: 80px" />
            </el-form-item>
          </el-row>

          <el-form-item prop="boxUsagePeriod" style="width:240px">
            <div style="width: 100%">
              <redStar />箱使期
            </div>
            <el-input-number v-model.trim="param.boxUsagePeriod" :disabled="isInfo" :controls="false" :min="0" :max="999" :precision="0"
              placeholder="< 1000" style="width: 100px" /> &nbsp;天
          </el-form-item>

          <el-form-item prop="inventory" style="width:240px">
            <div>
              <redStar />总库存
            </div>
            <el-input v-model="param.inventory" disabled style="width: 100%">
              <template #append>个</template>
            </el-input>
          </el-form-item>

          <!-- <el-form-item style="width:240px">
            <div>
              <redStar />上架方式
            </div>
            <el-select v-model="param.mode" style="width:100%" placeholder="选择还箱城市">
              <el-option v-for="item in param.modeList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item> -->

        </div>
      </el-card>
      <el-card  class="marginTop20">
        <span class="_before">发布人</span>
        <el-row align="middle">
          <el-col :offset="2" :span="2" class="text-right">出租人&nbsp;&nbsp;&nbsp;</el-col>
          <el-col :span="4" class="text-left"><el-input v-model="nickName" style="width: 240px" disabled placeholder="Please input"/></el-col>
        </el-row>
      </el-card>
      <el-card class="form_card" style="margin-top: 15px;">
        <span class="_before">图文描述</span>
        <div style="margin:40px 40px 0 40px">
          <el-form-item>
            <h3>
              <redStar />主图 <span style="color: #999;">(最多上传6张)</span>
            </h3>
            <div style="width:100%">
              <div class="div-box-dark">
                <upload-Img ref="uploadImgRef" :urlList="param.showMainImgList" @uploadSccess="uploadMainSccess"
                  @uploadRemoveSccess="uploadRemoveMainImgSccess" :disabledUpload="isInfo" style="width:1000px;height: 1000px;" />
                <p v-if="!isInfo">请上传 png/jpg 主图，大小不能超过3M，建议图片像素高于700*700px</p>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <h3>
              <redStar />详情描述 <span style="color: #999;">(详情大小最大不超过10M)</span>
              <div></div>
            </h3>
            <div style="width:100%;min-height:100px;min-width: 600px;">
              <div v-for="(mark, index) in param.marks" :key="index">
                <div style="background-color: #f4f4f5;box-sizing: border-box;padding: 10px;">
                  <upload-Img :ref="(el) => handleSetInputMap(el, index)" :disabledUpload="isInfo" :urlList="mark.imgInfo"
                    @uploadSccess="uploadDetailSccess($event, index)"
                    @uploadRemoveSccess="uploadRemoveDetailImgSccess($event, index)"
                    style="width:1000px;height: 1000px; " />
                  <el-input v-model="mark.textVal" placeholder="在这里介绍您的集装箱" :disabled="isInfo" type="textarea" rows="2" show-word-limit
                    maxlength="200" style="width: 90%;" />
                  <el-button :icon="CloseBold" type="info" circle @click="handleClose(index)"
                    style="width:10px;height:10px;margin-top: -30px;margin-left: 10px;" v-if="!isInfo"></el-button>
                </div>
              </div>
              <el-button :icon="Plus" type="info" size="small" @click="handleAdd" v-if="!isInfo">新增描述</el-button>
            </div>
          </el-form-item>
        </div>
      </el-card>

      <el-form-item v-if="!isInfo">
        <div style="height: 100px;width: 100%;"></div>
        <div v-if="param.isLoading" style="margin:auto;color: chocolate;">数据提交中......</div>
        <div v-else style="margin:auto;">
          <el-button @click="onSave('save')">保存待发布</el-button>
          <el-button v-if="!$route.query.secondaryEditing" type="primary" @click="onSave('putWarehouse')">放入仓库</el-button>
          <el-button type="primary" @click="onSave('publish')">立即发布</el-button>
        </div>
      </el-form-item>

    </el-form>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible" :title="param.operate == 'add' ? '新增' : '删除'" width="500">
      <el-input v-if="param.operate == 'add'" v-model="param.addElement"></el-input>
      <span v-else> 确认删除？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="param.dialogVisible = false">
            取消
          </el-button>
          <el-button @click="handleOk">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Plus, Delete, CloseBold } from '@element-plus/icons-vue'
import { computed, getCurrentInstance, onBeforeUnmount, onMounted, onUnmounted, reactive, ref, watch  } from 'vue';
import uploadImg from '@/components/upload/img.vue'
import citySelect from '@/components/citySelect'
import { saveBox, publishBox, editBox, editPublish, getBoxNum, getBoxInfo,boxEastInWarehouse } from '@/api/boxRent'
import { useRoute, useRouter } from 'vue-router';
import boxPriceList from '@/views/components/boxPriceList'
import { ElMessage, ElMessageBox } from 'element-plus';
import redStar from '@/views/components/redStar.vue';
import { uploadFile } from '@/api/system/upload'
import Cookies from "js-cookie";
import { bus } from '@/store/eventBus'

const $route = useRoute();
const router = useRouter();
const nickName = computed(()=>{
  return JSON.parse(Cookies.get("User-Info"))?.nickname
})

const validateLength = (rule: any, value: any, callback: any) => {
  const length = value.length
  if (length < 1 || length > 3) {
    callback(new Error('长度必须介于 1 和 3 之间'))
  } else {
    callback()
  }
}
const validateLength6 = (rule: any, value: any, callback: any) => {
  const length = value.length
  console.log(length)
  if (length < 1 || length > 6) {
    callback(new Error('长度必须介于 1 和 6 之间'))
  } else {
    callback()
  }
}//mainImgList
const validateMainImgList = (rule: any, value: any, callback: any) => {
  if (value) {
    const length = value.length
    if (length < 1) {
      callback(new Error('不能为空'))
    } else {
      callback()
    }
  } else {
    callback(new Error('不能为空'))
  }
}
const publishRules = {
  boxBackCity: [{ required: true, trigger: "change", message: "不能为空" }],
  boxStartCity: [{ required: true, trigger: "change", message: "不能为空" }],
  period: [
    { required: true, trigger: "blur", message: "不能为空" },
    { required: true, validator: validateLength, trigger: 'blur' },
  ],
  overdueFeeDay: [
    { required: true, trigger: "blur", message: "不能为空" },
    { required: true, validator: validateLength, trigger: 'blur' },
  ],
  lossFee: [
    { required: true, trigger: "blur", message: "不能为空" },
    { required: true, validator: validateLength6, trigger: 'blur' },
  ],
  lossDay: [
    { required: true, trigger: "blur", message: "不能为空" },
    { required: true, validator: validateLength, trigger: 'blur' },
  ],
  boxUsagePeriod: [
    { required: true, trigger: "blur", message: "不能为空" },
    { required: true, validator: validateLength, trigger: 'blur' },
  ],
  mainImgList: [
    { required: true, validator: validateMainImgList, trigger: 'blur' },
  ],
}

let param = reactive({
  boxSize: '40HQ',
  boxCase: [],
  boxCaseOld: [],
  loading: false,
  boxSizeHistory: {}, // eg:{40HQ:[{ size: string; info: any; price: string; num: string; }],20HQ:[],40GP:[],200GP:[]} 
  totalWeight: 1,
  weightOptions: [
    { value: 1, label: '30480' },
    { value: 2, label: '32500' },
  ],
  mode: 5,
  modeList: [
    { value: 5, label: '立即上架' },
    { value: 10, label: '放入仓库' },
  ],
  marks: [{ textVal: '',imgInfo: [] }],
  isOutBox: 10, //5-外调箱 10-不是外调箱
  dynamicTags: [],
  mainImgList: [],
  showMainImgList: [],
  overdueFeeDay: 10,
  lossDay: 10,
  lossFee: 10,
  boxUsagePeriod: 60,
  period: 15,
  caseList: [
    { value: 'fit', label: '适货' },
    { value: 'nextNew', label: '次新' },
    { value: 'allNew', label: '全新' },
    { value: 'mix', label: '混提' },
  ],
  sizeList: [
    { value: '40HQ', label: '40HQ' },
    { value: '40GP', label: '40GP' },
    { value: '20HQ', label: '20HQ' },
    { value: '20GP', label: '20GP' },
  ],
  boxStartCity: '',
  boxBackCity: '',
  boxStartCityData: {},
  boxBackCityData: {},
  startCityOptions: [],
  backCityOptions: [],
  dialogVisible: false,
  operate: '',
  addElement: '',
  addType: 'case', // case,size
  checkMonyType:'',
  status:false,
  isTrue:true,
  payCurrency:['CNY'],
  isCheckCNY:true, // 可结算币种默认选中
  isCheckUSD:false

})


onBeforeUnmount(() => {
  param.isLoading = false
})

const startCityList = ref(null)
const backCityList = ref(null)
const optId = ref(null)
const receivedValue = ref(null);
watch($route, async (val: any) => {
  showData(val);
})
const receiveData = (val: any) => {
    param.payCurrency = val
};
const isInfo=ref(false)
const showData = async (val: any) => {
  if (!val.query.row) return
  const row = JSON.parse(val.query.row)
  console.log
  let id = row.id // row.id 
  let isAdd = row.isAdd
  if(row?.isInfo){
    isInfo.value=row.isInfo
  }
  optId.value = id
  if (id) {
    console.log('edit')
    await getBoxInfo(id).then((res: any) => {
      const val = res.data
      console.log('res.data',res.data)
      // console.log(val)
      // return
      //城市展示
      startCityList.value = [{ value: val.carryCityId, label: val.carryCityName, countryId: val.carryCountryId, countryCName: val.carryCountryName }]
      backCityList.value = [{ value: val.returnCityId, label: val.returnCityName, countryId: val.returnCountryId, countryCName: val.returnCountryName }]
      param.boxStartCity = val.carryCityId
      param.boxBackCity = val.returnCityId
      // 城市数据/城市库存量
      startCityInfo(val.carryCityId, startCityList.value)

      param.totalWeight = val.totalWeight
      param.period = val.period
      param.payCurrency = val.payCurrency.split(',')
      param.overdueFeeDay = val.overdueFeeDay
      param.lossDay = val.lossDay
      param.lossFee = val.lossFee
      param.boxUsagePeriod = val.boxUsagePeriod
      param.mode = val.groundingMethod
      param.marks = JSON.parse(val.detailFileList) || []
      param.showMainImgList = JSON.parse(val.mainFileList)
      param.mainImgList = JSON.parse(val.mainFileList) // 校验 becareful
      param.dynamicTags = []
      val.releaseRentPriceList.forEach((item: any) => {
        let items = {
          boxType: item.boxType,
          boxCondition: item.boxCondition,
          unitPrice: item.unitPrice,
          totalWeight: item.totalWeight,
          inventory: item.inventory,
          currency: item.currency || 'CNY',
        }
        param.dynamicTags.push(items)
      })
      //编辑保存的入参
      param.boxStartCityData = {
        id: val.carryCityId,
        cityCName: val.carryCityName,
        countryId: val.carryCountryId,
        countryCName: val.carryCountryName,
      }
      param.boxBackCityData = {
        id: val.returnCityId,
        cityCName: val.returnCityName,
        countryId: val.returnCountryId,
        countryCName: val.returnCountryName,
      }
      // console.log(param.boxBackCityData)
      if(val.status == "10") {
        param.status = true
      }else {
        param.status = false
      }
    })
  }
  if (isAdd) {
    clearData()
  }
}

//清空数据
const clearData = () => {
  optId.value = null
  param.boxStartCity = ''
  param.boxBackCity = ''
  startCityList.value = [{}]
  backCityList.value = [{}]
  param.marks = [{ textVal: '', imgInfo: [] }]
  param.boxSize = '40HQ'
  param.boxCase = []
  param.loading = false
  param.boxSizeHistory = {}// eg={40HQ:[{ size: string; info: any; price: string; num: string; }],20HQ:[],40GP:[],200GP:[]} 
  param.totalWeight = 1
  param.dynamicTags = []
  param.showMainImgList = []
  param.status = false
}

// 提箱城市
const startCityInfo = async (id: any, data: any) => {
  param.boxStartCity = id
  param.boxStartCityData = data
  await getSetNumArry(id) // 获取城市对应 箱型库存 param.numArry
  boxPriceListRef.value.priceListSyncInventory() //注意执行顺序
}
const getSetNumArry = async (id: any) => {
  await getBoxNum(id).then((res: any) => {
    param.numArry = res.data || []
  })
}
const backCityInfo = (id: any, data: any) => {
  param.boxBackCity = id
  param.boxBackCityData = data
  // console.log(param.boxBackCityData)
}
const cityClear = (val: string) => {
  if (val == 'start') {
    param.numArry = []
    param.boxStartCity = ''
    param.boxStartCityData = {}
    param.dynamicTags = []
  }
  if (val == 'end') {
    param.boxBackCity = ''
    param.boxBackCityData = {}
  }
}

//更新list库存量
const outBoxChange = (val: any) => {
  param.dynamicTags.forEach((price: any) => {
    price.inventory = getNum(price.boxCondition, price.boxType)
  })
}
// 库存量
const getNum = (boxType, boxCondition) => {
  let num = 0
  const obj = param.numArry.find((item: any) => item.boxType == boxType && item.boxCondition == boxCondition)
  if (obj) {
    num = obj.inventory || 0
  }
  return num
}

//总库存
param.inventory = computed(() => {
  let num = 0
  param.dynamicTags.forEach((el: any) => {
    num += parseInt(el.inventory)
  })
  return num
})

const handleClose = (val: any) => {
  param.marks.splice(val, 1)
}
const handleAdd = (val: any) => {
  param.marks.push({ textVal: '', imgInfo: [] })
}

const handleOk = () => {
  param.dialogVisible = false
  if (param.operate == 'add') {
    // console.log(param.addType)
    if (param.addType == 'case') {
      let index = param.caseList.length
      param.caseList.push({ value: 'addElement' + index, label: param.addElement })
    }
    if (param.addType == 'size') {
      param.sizeList.push({ value: param.addElement, label: param.addElement })
    }
    param.addElement = ''
  }
  if (param.operate == 'delete') {
    if (param.addType == 'size') {// param.boxSize
      const index = param.sizeList.findIndex((item: any) => {
        return item.value == param.boxSize
      })
      if (index != -1) {
        param.sizeList.splice(index, 1)
      }
    }
    if (param.addType == 'case') {//param.boxCase
      param.boxCase.map((val: any) => {
        let index = param.caseList.findIndex((item: any) => {
          return item.value == val
        })
        if (index != -1) {
          // indexList.push(index)
          param.caseList.splice(index, 1)
        }
      })
    }
  }
}

//上传成功的 
const uploadMainSccess = (data: any) => {
  param.showMainImgList.push(data)
}
const uploadDetailSccess = (data: any, index: number) => {
  let mark = param.marks[index]
  mark.imgInfo.push(data)
}

//img删除成功
const uploadRemoveMainImgSccess = (data: any) => {
  let index = param.showMainImgList.findIndex((item: any) => {
    return item.uid == data.uid
  })
  if (index != -1) {
    param.showMainImgList.splice(index, 1)
  }
}
const uploadRemoveDetailImgSccess = (data: any, index: number) => {
  let mark = param.marks[index]
  let index1 = mark.imgInfo.findIndex((item: any) => {
    return item.uid == data.uid
  })
  if (index1 != -1) {
    mark.imgInfo.splice(index1, 1)
  }
  if (mark.imgInfo.length == 0 && !mark.textVal) {
    param.marks.splice(index, 1)
  }
}

//upload img
const uploadImgRef = ref()
const uploadRef = {}
const handleSetInputMap = (el, index: number) => {
  if (el) {
    uploadRef[`imgRef${index}`] = el;
  }
};

//上传文件
const uploadFile = async (file: any) => {
  let result: any = {}
  let formData = new FormData()
  formData.append('file', file.raw)
  await uploadFile(formData).then((res: any) => {
    result = res.data
  })
}

// 保存/发布
const { proxy } = getCurrentInstance();
const boxPriceListRef = ref({ priceList: [] })
const onSave = async (opr: any) => {
  const isExist = boxPriceListRef.value.isExist
  if (isExist) {
    return ElMessage.warning('请处理重复数据！')
  }
  const carry = param.boxStartCityData
  const back = param.boxBackCityData
  let template = {
    "carryCityId": carry.id,
    "carryCityName": carry.cityCName,
    "carryCountryId": carry.countryId,
    "carryCountryName": carry.countryCName,
    "returnCityId": back.id,
    "returnCityName": back.cityCName,
    "returnCountryId": back.countryId,
    "returnCountryName": back.countryCName,
    "isOutBox": param.isOutBox,
    "totalWeight": param.totalWeight || 32500,
    "period": param.period,
    "boxUsagePeriod": param.boxUsagePeriod,
    "overdueFeeDay": param.overdueFeeDay,
    "overdueFeeCurrency": "USD", // 超期费，只有美元-业务已确认
    "lossDay": param.lossDay,
    "lossFee": param.lossFee,
    "groundingMethod": param.mode, //上架方式 5-立即上架  10-放入仓库
    "mainFileList": JSON.stringify(param.showMainImgList), //主图
    "detailFileList": JSON.stringify(param.marks), //详情信息 textVal
    "remark": "我是备注", //jcbug
    "releaseRentPriceList": boxPriceListRef.value.getPriceList(),
    "payCurrency":param.payCurrency.join(","),//可结算币种 
  }
  param.isLoading = true
  if (optId.value) {
    template.id = optId.value
  }
  if (opr == 'save') { // 保存待发布
    saveBox(template).then((res: any) => {
      param.isLoading = false
      router.push('myOutBox')
    }).catch((err: any) => {
      setTimeout(() => {
        param.isLoading = false
      }, 2000)
    })
  }
  if(opr == 'putWarehouse'){ //放入仓库
    console.log('putWarehouse',template)
    await boxEastInWarehouse(template).then((res: any) =>{
      console.log('放入仓库',res)
      param.isLoading = false
      router.back()
    }).catch((err: any) => {
      setTimeout(() => {
        param.isLoading = false
      }, 2000)
    })

  }
  if (opr == 'publish') { //立即发布
    proxy.$refs.publishRef.validate(valid => {
      if (!valid) {
        param.isLoading = false
        return
      }
      if (param.showMainImgList.length === 0) {
        param.isLoading = false
        return ElMessage.warning('请上传主图！')
      }
      if (param.marks.length == 0 || !param.marks[0].imgInfo || param.marks[0].imgInfo.length === 0) {
        param.isLoading = false
        return ElMessage.warning('请上传详情图！')
      }
      publishBox(template).then((res: any) => {
        param.isLoading = false
        router.push('myOutBox')
      }).catch((err: any) => {
        setTimeout(() => {
          param.isLoading = false
        }, 2000)
      })
    })
  }
}
//根据租箱规格选择的币种 筛选可结算币种
const publishCurrency = (val: any) => {
  param.payCurrency.length = 0 
  param.payCurrency.push(val)
  if(val =="CNY"){
    param.isCheckCNY = true
    param.isCheckUSD = false
  }else if(val == "USD"){
    param.isCheckCNY = false
    param.isCheckUSD = true
  }
}

let initialData: any;
onMounted(() => {
  initialData = structuredClone(JSON.parse(JSON.stringify(param)))
  showData($route)
})

import _ from 'lodash'
// 组件B
bus.on('call-b', () => {
  // if(isInfo.value){
  //   return false
  // }
  if(!_.isEqual(initialData,param) && !isInfo.value){
    ElMessageBox.confirm('存在未保存数据，确定离开吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ElMessageBox.close();
        bus.emit('b-response', 'next')
      }).catch(() => {
        ElMessageBox.close();
        bus.emit('b-response', 'stop')
      })
  }else{
    ElMessageBox.close();
    bus.emit('b-response', 'next')
  }
})


onUnmounted(() => {
    // bus.off('call-b', handleCallB); // 重要：清理事件监听
});

</script>

<style scoped></style>